<template>
  <!---搜索表单-->
  <div class="search-div">
    <el-form label-width="70px" size="small">
      <el-row>
        <el-col :span="6">
          <el-form-item label="关键字">
            <el-input
              style="width: 100%"
              placeholder="用户名"
              v-model="queryDto.keyword"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="创建时间">
            <el-date-picker
              type="daterange"
              range-separator="To"
              start-placeholder="开始时间"
              end-placeholder="结束时间"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              style="width: 100%"
              v-model="createTimes"
              clearable
            />
          </el-form-item>
        </el-col>
        <el-col :span="1"></el-col>
        <el-col :span="5">
          <el-button type="primary" size="small" @click="searchSysUser">
            搜索
          </el-button>
          <el-button size="small">重置</el-button>
        </el-col>
      </el-row>
    </el-form>
  </div>

  <!--添加按钮-->
  <div class="tools-div">
    <el-button type="success" size="small" @click="addShow">添 加</el-button>
  </div>

  <el-dialog v-model="dialogVisible" title="添加或修改" width="40%">
    <el-form label-width="120px">
      <el-form-item label="用户名">
        <el-input v-model="sysUser.username" style="width: 240px" />
      </el-form-item>
      <el-form-item v-if="sysUser.id == null" style="width: 340px" label="密码">
        <el-input type="password" show-password v-model="sysUser.password" />
      </el-form-item>
      <el-form-item label="手机">
        <el-input v-model="sysUser.phone" style="width: 240px" />
      </el-form-item>
      <el-form-item label="头像">
        <el-upload
          class="avatar-uploader"
          action="http://localhost:8501/admin/system/fileUpload"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :headers="headers"
        >
          <img v-if="sysUser.avatar" :src="sysUser.avatar" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon"></el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="描述">
        <el-input v-model="sysUser.description" style="width: 240px" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>

  <!---数据表格-->
  <el-table :data="list" style="width: 100%">
    <el-table-column prop="username" label="用户名" />
    <el-table-column prop="phone" label="手机" />
    <el-table-column prop="avatar" label="头像" #default="scope">
      <img :src="scope.row.avatar" width="50" />
    </el-table-column>
    <el-table-column prop="description" label="描述" />
    <el-table-column prop="status" label="状态" #default="scope">
      {{ scope.row.status == 1 ? '正常' : '停用' }}
    </el-table-column>
    <el-table-column prop="createTime" label="创建时间" />
    <el-table-column label="操作" align="center" width="280" #default="scope">
      <el-button type="primary" size="small" @click="editUserShow(scope.row)">
        修改
      </el-button>
      <el-button type="danger" size="small" @click="deleteUser(scope.row)">
        删除
      </el-button>
      <el-button type="warning" size="small" @click="showAssignRole(scope.row)">
        分配角色
      </el-button>
    </el-table-column>
  </el-table>

  <el-pagination
    :page-sizes="[10, 20, 50, 100]"
    layout="total, sizes, prev, pager, next"
    :total="total"
    v-model:current-page="pageParams.page"
    v-model:page-size="pageParams.limit"
    @size-change="fetchData"
    @current-change="fetchData"
  />

  <el-dialog v-model="dialogRoleVisible" title="分配角色" width="40%">
    <el-form label-width="80px">
      <el-form-item label="用户名">
        <el-input disabled v-model="sysUser.username"></el-input>
      </el-form-item>
      <el-form-item label="角色列表">
        <el-radio-group v-model="sysUserRole.roleId">
          <el-radio v-for="role in allRoles" :key="role.id" :label="role.id">
            {{ role.roleName }}
          </el-radio>
        </el-radio-group>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="saveUserRole">提交</el-button>
        <el-button @click="dialogRoleVisible = false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import {
  deleteSysUserApi,
  GetSysUserListByPage,
  saveSysUser,
  saveUserRoleApi,
  updateSysUser
} from '@/api/sysUser.js'
import { ElMessage } from 'element-plus' // 表格数据模型
import { useUserStore } from '@/stores/index.js'
import { getAllRoleListApi } from '@/api/sysRole.js'

const userStore = useUserStore()
const headers = {
  token: userStore.token // 从pinia中获取token，在进行文件上传的时候将token设置到请求头中
}

// 表格数据模型
const list = ref([])

// 定义提交表单数据模型
const defaultForm = {
  userName: '',
  phone: '',
  password: '',
  description: '',
  avatar: ''
}
const sysUser = ref(defaultForm)

// 分页条数据模型
const total = ref(0)
// 定义一个查询模型
const queryDto = ref({ keyword: '', createTimeBegin: '', createTimeEnd: '' })
const createTimes = ref([])

// 分页数据模型
const pageParamsForm = {
  page: 1,
  limit: 10
}

const allRoles = ref([])
const defaultUserRole = {
  roleId: '',
  userId: ''
}
const sysUserRole = ref(defaultUserRole)
const dialogRoleVisible = ref(false)
const showAssignRole = async (row) => {
  sysUser.value = { ...row }
  dialogRoleVisible.value = true
  // 查询所有的角色数据
  const response = await getAllRoleListApi()
  console.log('dataAllrole' + response.data.allRoles)
  console.log(JSON.stringify(response.data.allRoles, null, 2))

  allRoles.value = response.data.allRoles
  console.log('allRoles' + allRoles.value)
}

//为用户分配角色
const saveUserRole = async () => {
  sysUserRole.value.userId = sysUser.value.id
  await saveUserRoleApi(sysUserRole.value)
  dialogRoleVisible.value = false
  sysUserRole.value.roleId = ''
  fetchData()
  ElMessage.success('操作成功')
}
const pageParams = ref(pageParamsForm)
const fetchData = async () => {
  console.log('createTimes' + createTimes.value)
  if (createTimes.value != null) {
    //判断时间选择框是否有值
    if (createTimes.value.length == 2) {
      queryDto.value.createTimeBegin = createTimes.value[0]
      queryDto.value.createTimeEnd = createTimes.value[1]
    }
  } else {
    queryDto.value.createTimeBegin = ''
    queryDto.value.createTimeEnd = ''
  }

  const response = await GetSysUserListByPage(
    pageParams.value.page,
    pageParams.value.limit,
    queryDto.value
  )
  total.value = response.data.total
  list.value = response.data.records
}
onMounted(() => {
  fetchData()
})
const searchSysUser = () => {
  fetchData()
}
// 添加表单对话框显示隐藏控制变量
const dialogVisible = ref(false)
const addShow = () => {
  sysUser.value = {}
  dialogVisible.value = true
}
const submit = async () => {
  //增加判断场景，是新增还是编辑
  if (!sysUser.value.id) {
    const resposne = await saveSysUser(sysUser.value)
    if (resposne.code === 200) {
      dialogVisible.value = false
      ElMessage.success('操作成功')
      fetchData()
    } else {
      ElMessage.error(resposne.message)
    }
  } else {
    const resposne = await updateSysUser(sysUser.value)
    if (resposne.code === 200) {
      dialogVisible.value = false
      ElMessage.success('操作成功')
      fetchData()
    } else {
      ElMessage.error(resposne.message)
    }
  }
}
const editUserShow = (row) => {
  dialogVisible.value = true
  sysUser.value = { ...row }
}
const deleteUser = async (row) => {
  sysUser.value = { ...row }
  await deleteSysUserApi(sysUser.value.id)
  ElMessage.success('操作成功')
  fetchData()
}

// 图像上传成功以后的事件处理函数
// eslint-disable-next-line no-unused-vars
const handleAvatarSuccess = (response, uploadFile) => {
  sysUser.value.avatar = response.data
}
</script>

<style scoped>
.search-div {
  margin-bottom: 10px;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.tools-div {
  margin: 10px 0;
  padding: 10px;
  border: 1px solid #ebeef5;
  border-radius: 3px;
  background-color: #fff;
}
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
  background: url('@/assets/avatar.jpg') no-repeat center / 220px auto;
}
</style>
